public class Leetcode1669 {
    public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {
        ListNode list2LastNode = list2;
        while (list2LastNode.next != null) {
            list2LastNode = list2LastNode.next;
            if (list2LastNode.next == null) {
                break;
            }
        }

        ListNode list1ANode = list1;

        int i = 0;
        while (i != a - 1) {
            list1ANode = list1ANode.next;
            i++;
        }

        ListNode list1BNode = list1ANode;
        while (i != b) {
            list1BNode = list1BNode.next;
            i++;
        }

        if (list1ANode.val == a) {
            list2LastNode.next = list1BNode;
            return list2;
        } else {
            list1ANode.next = list2;
            list2LastNode.next = list1BNode.next != null ? list1BNode.next : null;
            return list1;
        }
    }


}

